
local skynet     = require "skynet"
local show       = require "showmsg"
local manager    = require "manager"
local socket     = require "socket"
local char       = require "char.char"
local SQL        = require "sql"
local superclass = require "superclass"


local host
local send_request



local M = {}


-- 角色的登录验证
function M:token_auth(client, fd, response)

    
    skynet.call("global_manager", "lua", "mgr_add", "account_manager",client.session, client)  

    show:debug("令牌 session = %d token = %s 到管理器中",  client.session, client.token)

    return false

end 

-- 验证角色的信息是否正确
function M:auth(client, fd, response)

  
    if not client and fd then 
        return true 
    end 
    
    -- 获取回话信息
    local token = skynet.call("global_manager", "lua", "mgr_get","account_manager", client.session)
    
    if not token then 
        
        if response then 
                socket:send_package(fd, response({result = 18}))
        end  

        return  false 
    end 
    
    -- 判断回话信息已经密码是否正确
    if client.session == token.session and client.token == token.token then 


        show:debug("账户 session = %d  token = %s 通过认证", client.session, client.token)
       
        local onlinechar = char:create_online_char_data(token.account_id)
        onlinechar.fd     = fd
        onlinechar.server = "char_server"
        
        -- 先移除回话
       -- account_manager:remove(client.session)
        skynet.call("global_manager", "lua", "mgr_remove", "account_manager",client.session)  

        -- 将数据保存到账户管理器中
       -- account_manager:add(fd, onlinechar)

       skynet.call("global_manager", "lua", "mgr_add", "account_manager", fd, onlinechar)  
        
        if response then 

            socket:send_package(fd, response({result = 0}))
        end       
               
    else  

        --show:debug("无效的 session = %d  token = %s",client.session, client.token)
        skynet.error("效验无效 验证",client.session, client.token)
        if response  then 

            socket:send_package(fd, response({result = 18}))
        end 

        --[[
        return {result = 18}
        ]]--
     
    end 

    return false
end 


-- 初始化
function M:init()

    account_manager = skynet.call("global_manager","lua","get", "account_manager")
  
  
    -- 如果不存在则创建
    if not account_manager then 

        account_manager = manager:new()

        if not account_manager then
            show:warning("创建 %s 管理器失败", "account_manager")
            return true 
        end
         
        
        skynet.call("global_manager", "lua", "add", "account_manager", account_manager)          
        show:debug("创建 account 管理已创建")
    end 

    if char:do_init(SQL:new_sql_handler(), {
		host 		= "127.0.0.1",
		port 		= 3306,
		basename 	= "Account",
		user 		= "root",
		pawd 		= "123123"
	}) then 

        return true 
    end  
    
    return false
end 

local handler = superclass:new(M,char)

return handler